package net.esj.basic.dao.jdbc.jpa;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * 读取配置文件，构建SessionFactory。
 */
public class Configuration {
	Map properties = new HashMap();
	List<String> mappings = new ArrayList();
	public Configuration configure(){
		return configure("/miniorm.cfg.xml");
	}
	/**
	 * 读取配置文件。
	 * @param xmlPath
	 * @return
	 */
	public Configuration configure(String xmlPath){
        InputStream in = Configuration.class.getResourceAsStream(xmlPath); 
        DocumentBuilderFactory factory = DocumentBuilderFactory  
                .newInstance();
        DocumentBuilder builder;
        Document doc = null;
		try {
			builder = factory.newDocumentBuilder();
			doc = builder.parse(in);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(),e);
		}
		NodeList nodes = doc.getElementsByTagName("property");
		properties = new HashMap();
		for (int i = 0; i < nodes.getLength(); i++) {
			Element ele = (Element)nodes.item(i);
			//现在很简单只有几个属性
			String name = ele.getAttribute("name");
			String value = null;
			Node firstChild = ele.getFirstChild();
			if(firstChild != null)value = firstChild.getNodeValue().trim();
			properties.put(name, value);
		}
		NodeList mappingNodes = doc.getElementsByTagName("mapping");
		for (int i = 0; i < mappingNodes.getLength(); i++) {
			Element ele = (Element)mappingNodes.item(i);
			//现在很简单只有几个属性
			String klass = ele.getAttribute("class");
			mappings.add(klass);
		}
		return this;
	}
	/**
	 * 创建一个SessionFactory对象。
	 * @return
	 */
	public SessionFactory buildSessionFactory(){
		String sessionFactoryStr = (String) properties.get("sessionFactory");
		String connectionProviderStr = (String) properties.get("connectionProvider");
		try {
			SessionFactory sessionFactory = (SessionFactory) Class.forName(sessionFactoryStr).newInstance();
			ConnectionProvider connectionProvider = (ConnectionProvider) Class.forName(connectionProviderStr).newInstance();
			connectionProvider.init(properties);
			sessionFactory.setConnectionProvider(connectionProvider);
			
			for (String klass : mappings) {
				Class entityType = Class.forName(klass);
				sessionFactory.registerEntityType(entityType);
			}
			return sessionFactory;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(),e);
		}
		
	}
}
